package net.maergaiyun.controller;


import net.maergaiyun.controller.request.TrafficPageRequest;
import net.maergaiyun.controller.request.UseTrafficRequest;
import net.maergaiyun.service.TrafficService;
import net.maergaiyun.util.JsonData;
import net.maergaiyun.vo.TrafficVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author maergaiyun
 * @since 2024-07-31
 */
@RestController
@RequestMapping("/api/traffic/v1")
public class TrafficController {

    @Autowired
    private TrafficService trafficService;

    @Value("${rpc.token}")
    private String rpcToken;

    /**
     * 分页查询可用流量包
     *
     * @param request
     * @return
     */
    @RequestMapping("page")
    public JsonData pageAvailable(@RequestBody TrafficPageRequest request) {
        Map<String, Object> pageMap = trafficService.pageAvailable(request);
        return JsonData.buildSuccess(pageMap);
    }

    @GetMapping("/detail/{trafficId}")
    public JsonData detail(@PathVariable("trafficId") Long trafficId) {
        TrafficVO trafficVO = trafficService.detail(trafficId);
        return JsonData.buildSuccess(trafficVO);
    }

    /**
     * 使用扣减流量包
     *
     * @param trafficRequest
     * @param request
     * @return
     */
    @PostMapping("reduce")
    public JsonData useTraffic(@RequestBody UseTrafficRequest trafficRequest, HttpServletRequest request) {
        String requestToken = request.getHeader("rpc-token");
        if (rpcToken.equalsIgnoreCase(requestToken)) {
            JsonData jsonData = trafficService.reduce(trafficRequest);
            return jsonData;
        } else {
            return JsonData.buildError("非法访问");
        }
    }
}

